-- Count access token 
-- Written by Kevin.XU
-- 2016/8/16

--[[
Request body:::
{
    "service_type":"SHOPPING"
}
Response body:::
{
    "count":188,
    "status":0,
    "status_desc":""
}
]]

ngx.req.read_body()

local resty_redis = require "resty.redis"
local resty_cjson = require "cjson"
local resty_md5 = require "resty.md5"
local resty_string = require "resty.string"
local limit_toolkit = require "ddtk.limit_tk"
local redis_config = require "ddtk.redis_config"

local max_idle_timeout = 300*1000
local pool_size = 20
local timeout = 1000

--make response
local resp={}

--read request body and make token value
local now=os.time()
local json_request_body_data = ngx.req.get_body_data()
local request_body = resty_cjson.decode(json_request_body_data) 
local service_type = request_body.service_type

--get redis address
local redis_ip,redis_port = redis_config.select_slave_redis_node(service_type)
if redis_ip == nil then
    ngx.log(ngx.ERR, "not found redis")
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end
local red = resty_redis:new()
red:set_timeout(timeout)
local ok, err = red:connect(redis_ip, redis_port)
if not ok then
    ngx.log(ngx.ERR, "connect failed")
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end
--try to find token value from redis
local count, err2 = red:dbsize()
resp['count']=count
resp['status']=0
resp['status_desc']=''

--keep connection alive
red:set_keepalive(max_idle_timeout, pool_size)


local resp_json = resty_cjson.encode(resp) 


ngx.say(resp_json)

